import { shallowRef, reactive, onMounted, watch } from 'vue';
import type { Ref } from 'vue';

interface TableProps {
  page: number;
  pageSize: number;
  total: number;
  loading: boolean;
}

interface FetchParams {
  page: number;
  pageSize: number;
  query?: Record<string, any>;
}

export function useTable<T>(
  fetchApi: (
    params: FetchParams
  ) => Promise<{ data: { data: T[]; total: number } }>
) {
  // 将不需要响应式嵌套的内容单独处理
  const tableProps = reactive<TableProps>({
    page: 1,
    pageSize: 10,
    total: 0,
    loading: false,
  });

  // 使用 shallowRef 避免深度解包
  const data: Ref<T[]> = shallowRef<T[]>([]);

  const queryParams = shallowRef<Record<string, any>>({}); // 查询参数

  const fetchData = async () => {
    tableProps.loading = true;
    try {
      const response = await fetchApi({
        page: tableProps.page,
        pageSize: tableProps.pageSize,
        query: queryParams.value,
      });

      // 直接赋值给 ref 类型，通过类型断言解决类型问题
      data.value = response.data.data;
      tableProps.total = response.data.total;
    } catch (error) {
      console.error('数据加载失败:', error);
    } finally {
      tableProps.loading = false;
    }
  };

  const handlePageChange = (newPage: number) => {
    tableProps.page = newPage;
    fetchData();
  };

  const handlePageSizeChange = (newSize: number) => {
    tableProps.pageSize = newSize;
    fetchData();
  };

  const handleQueryChange = (newQuery: Record<string, any>) => {
    queryParams.value = newQuery;
    fetchData();
  };

  onMounted(() => {
    fetchData();
  });

  watch(queryParams, () => {
    tableProps.page = 1;
    fetchData();
  });

  return {
    tableProps,
    data, // 返回数据
    handlePageChange,
    handlePageSizeChange,
    handleQueryChange,
  };
}
